<?php 
	include_once("../connect.php");
	include_once("../comment_model.php");
	include_once("../user_model.php");
	include_once("../utility.php");
	
	session_start();
	
	mysql_select_db("progin_171_13509047",$con);	

	$q=$_POST["q"];

	if($q=="add-comment") {	
		$comment_model = new Comment_Model();		
		//dapetin user id yang sedang login dari session
		$logged_in_user_id = $_SESSION["userid"];	
		
		$content='';
		$errorFlag = false;
		$errors = array("content"=>"");
		
		if(isset($_POST['content'])) {
			$content = $_POST['content'];			
		}
		if(isset($_POST['post_id'])) {
			$post_id = $_POST['post_id'];
		}
		if(isset($_POST['logged_in_user_id'])){
			$logged_in_user_id = $_POST['logged_in_user_id'];
		}

		//clean
		$content = mysql_real_escape_string($content);
		
		//validasi komen box	
		if(strlen($content)==0) {
			$errors['content'] = "Comment box can't be empty!";
			$errorFlag = true;
		}
		
		if(!$errorFlag) {
			//lolos validasi 	
			$ret = $comment_model->insertComment($logged_in_user_id, $post_id, $content);					
			if($ret!=false) {							
				//kembalikan response komentar barusan oleh user	
				$comment_res = $comment_model->getAllComment($post_id);	
				if($comment_res!=false) {
					while($row = mysql_fetch_array($comment_res)) {
					
						$comment_datetime = new DateTime($row['datetime'], new DateTimeZone('Asia/Jakarta'));	
						$now = new DateTime(null, new DateTimeZone('Asia/Jakarta'));	
						$comment_diff_datetime_string = Utility::getDeltaTimeString($comment_datetime, $now);
					
						echo '<div class="content-comment" id="comment'.$row['comment_id'].'">' ;
						echo '<img class="avatar" src="avatar/'.$row['avatar'].'" />';
						echo '<h4>'.$row['username'].'</h4>' ;
						echo '<p>'.$row['content'].'</p>' ;						
						echo '<span name="comment-date"><small>'.$comment_diff_datetime_string.'</small></span>' ;						
						if($row['username_id']==$logged_in_user_id)
							echo '<input type="button" onclick="delComment('.$row['comment_id'].');" value="delete" />';
						echo '</div>' ;
					}					
				}				
				
			}else echo "error inserting comment ";
		}else{
			echo "error \n";
			foreach($errors as $error) {
				echo $error." \n";
			}
		}		
	}else if($q=="del-comment") {
		$comment_model = new Comment_Model();
		//dapetin user id yang sedang login dari session
		$logged_in_user_id = $_SESSION["userid"];		
				
		if(isset($_POST['comment_id'])) {
			$comment_id = $_POST['comment_id'];			
		}		

		//cocokin user yang sedang login sekarang apakah sama dengan user yang ngepos komentar tersebut
		$comment_res = $comment_model->getComment($comment_id);
		$row = mysql_fetch_array($comment_res);
		if($row['username_id']==$logged_in_user_id) {
			$ret = $comment_model->delComment($comment_id);
			if($ret) 
				echo $comment_id;	
		}else{
			echo "error violation access\n";
		}		
	}

	include_once("../close_con.php");
?>